package com.test.thread.pool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutorDemo {

	static BlockingQueue<Integer> warehouse = new ArrayBlockingQueue<Integer>(100);

	static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, // 核心线程数：池中所保存的线程数，包括空闲线程
			20, // 池中允许的最大线程数
			1, // 当线程数大于核心时，此为终止前多余的空闲线程等待新任务的最长时间
			TimeUnit.SECONDS, // keepAliveTime 参数的时间单位
			new LinkedBlockingQueue(20)
	// 执行前用于保持任务的队列。此队列仅保持由 execute 方法提交的 Runnable 任务。
	);

	public static void main(String[] args) {
		// 预备数据：填满整个队列
		for (int i = 0; warehouse.remainingCapacity() > 0; i++) {
			warehouse.offer(i);
		}

		// 线程池执行：
		for (int i = 0; i < 35; i++) {
			threadPool.execute(new PrintIntThread(warehouse));
		}

		// 令这些任务都执行完后关闭线程池
		threadPool.shutdown();
	}

}

class PrintIntThread implements Runnable {

	static BlockingQueue<Integer> warehouse;

	public PrintIntThread(BlockingQueue<Integer> warehouse) {
		this.warehouse = warehouse;
	}

	public void run() {
		while (warehouse.size() > 0) {
			try {
				System.out.println(Thread.currentThread().getName() + " 取出了" + warehouse.take());
				Thread.sleep((int) (Math.random() * 300)); // 为便于观察
				// 随机等待300ms内的时间
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}